// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database(),
  _ = db.command,
  $ = _.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const {
    cmd
  } = event

  try {
    if (cmd == 'getShopUsers') {
      return await getShopUsers(event) // { userId | userOpenId, resultType }
    } else if (cmd == 'findDeliveryUsers') {
      return await findDeliveryUsers(event)
    } else if (cmd == 'findUserByMobile') {
      return await findUserByMobile(event)
    } else if (cmd == 'findOrdersByMobile') {
      return await findOrdersByMobile(event)
    }
  } catch (e) {
    return e
  }

  return 'unknown command'
}

async function findUserByMobile(event) {
  const mobile = event.mobile,
    field = event.field || {
      _id: true,
      _openid: true
    }
  let userRes = await db.collection('users')
    .where({
      phoneNumber: _.eq(mobile)
    })
    .field(field)
    .get()
  if (userRes?.data.length > 0) return userRes.data[0]

  const addrRes = await db.collection('delivery_addr')
    .where({
      mobile: _.eq(mobile)
    })
    .field({
      _openid: true
    })
    .get()
  if (addrRes?.data.length > 0) {
    const addr = addrRes.data[0]
    userRes = await db.collection('users')
      .where({
        _openid: _.eq(addr._openid)
      })
      .field(field)
      .get()
    if (userRes?.data.length > 0) {
      return userRes.data[0]
    }
  }

  return {}
}

async function findOrdersByMobile(event) {
  const mobile = event.mobile,
    field = event.field || {
      _id: true,
      _openid: true
    }
  return await db.collection('orders')
    .aggregate()
    .lookup({
      from: 'delivery_addr', // 关联的集合名
      localField: '_openid', // 当前集合的关联字段
      foreignField: '_openid', // 目标集合的关联字段
      as: 'addressInfo' // 输出数组字段名
    })
    .unwind('$addressInfo') // 展开关联数组
    .match({
      'addressInfo.mobile': mobile // 匹配手机号
    })
    .project({
      _id: 1, // 返回订单ID
      ...field
    })
    .end()
}

/**
 * 获取同店用户（返回openid数组）
 */
async function getShopUsers(event) {
  const {
    userId,
    userOpenId,
    resultType
  } = event

  const userRes = await db.collection('users')
    .where({
      _id: userId ? _.eq(userId) : _.exists(true),
      _openid: userOpenId ? _.eq(userOpenId) : _.exists(true)
    })
    .get()
  const user = userRes.data[0]

  const resultUsers = [],
    limit = 100
  let skip = 0
  while (true) {
    const addrRes = await db.collection('delivery_addr')
      .where({
        shop: _.eq(user.shop.id + '').or(_.eq(Number(user.shop.id)))
      })
      .skip(skip)
      .limit(limit)
      .get()
    const addrs = addrRes.data
    for (const addr of addrs) {
      resultUsers.push((resultType || 'id') == 'openid' ? addr._openid : addr._id)
    }
    skip += limit
    if (addrs.length < limit) break
  }

  return resultUsers
}

async function findDeliveryUsers(event) {
  const {
    orderId
  } = event
  const _ = db.command
  // order信息
  const orderRes = await db.collection('orders')
    .where({
      _id: _.eq(orderId)
    })
    .get()
  const order = orderRes.data[0]
  // console.log(order)

  // 用户地址
  const addrRes = await db.collection('delivery_addr')
    .where({
      _openid: _.eq(order._openid)
    })
    .get()
  const addr = addrRes.data[0]
  // console.log(addr)

  // 配送员或店长
  const strShopId = addr.shop + '',
    nShopId = parseInt(addr.shop + '')
  const userRes = await db.collection('users')
    .where(_.and({
      role: _.or(_.eq('delivery'), _.eq('master')),
    }, _.or({
      shops: strShopId
      // {
      //   id: nShopId
      // }
    }, {
      shop: nShopId
      // {
      //   id: strShopId
      // }
    })))
    .get()
  const deliveryMen = userRes.data
  // console.log(addr, deliveryMen)
  return {
    order,
    addr,
    deliveryMen
  }
}